<template>
  <a-drawer v-model:visible="visible" title="数据录入" :width="width >= 600 ? 600 : '100%'" :footer="false">
    <a-row>
      <a-upload :show-file-list="false" :custom-request="handleUpload">
        <template #upload-button>
          <a-button type="primary" shape="round">
            <template #icon>
              <icon-upload />
            </template>
            <template #default>上传数据</template>
          </a-button>
        </template>
      </a-upload>
    </a-row>
    <a-row v-if="state.isLoad">
      <a-image width="450" :src="state.result[0]" />
      <!-- <a-image width="450" :src="state.result[1]" />
      <a-image width="450" :src="state.result[2]" />
      <a-image width="450" :src="state.result[3]" /> -->
    </a-row>
    <a-row>
    </a-row>
  </a-drawer>
</template>

<script setup lang="ts">
import { Message, type RequestOption } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { type InfoDetailResp, getInfo as getDetail } from '@/apis/task/info'
import { dataReadTimeDomainWaveform } from '@/apis/task/dataRead'
import { uploadFile } from '@/apis'

const { width } = useWindowSize()

const dataId = ref('')
const dataDetail = ref<InfoDetailResp>()
const visible = ref(false)

// 查询历史数据解析详情
const getDataDetail = async () => {
  const { data } = await getDetail(dataId.value)
  dataDetail.value = data
}

const state = reactive({
  data: '',
  result: [],
  isLoad: false,
})

const clearState = () => {
  state.data = ''
  state.result = []
  state.isLoad = false
}

// 打开
const onOpen = async (id: string) => {
  clearState()
  dataId.value = id
  await getDataDetail()
  visible.value = true
}

// 上传
const handleUpload = (options: RequestOption) => {
  const controller = new AbortController()
    ; (async function requestWrap() {
      const { onProgress, onError, onSuccess, fileItem, name = 'file' } = options
      onProgress(20)
      const formData = new FormData()
      formData.append(name as string, fileItem.file as Blob)
      try {
        const res = await uploadFile(formData)
        Message.success('上传成功')
        state.data = res.data.url
        onSuccess(res)
        debugger
        // 解析数据获得时域信号波形图
        const timeDomainWaveform = await dataReadTimeDomainWaveform(state.data)
        state.result[0] = timeDomainWaveform.data
        state.isLoad = true
        console.log(state)
      } catch (error) {
        onError(error)
      }
    })()
  return {
    abort() {
      controller.abort()
    },
  }
}
defineExpose({ onOpen })
</script>

<style scoped lang="scss"></style>
